package com.wellview.template.view;

import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bumptech.glide.Glide;
import com.wellview.template.App;
import com.wellview.template.BaseActivity;
import com.wellview.template.Constant;
import com.wellview.template.R;
import com.wellview.template.bean.StartBean;
import com.wellview.template.logger.Logger;
import com.wellview.template.modle.BehaviorFactory;
import com.wellview.template.modle.SplashBehavior;
import com.wellview.template.utils.EventCenter;
import com.wellview.template.utils.NetTools;
import com.wellview.template.utils.ScreenUtil;
import com.wellview.template.utils.SharePrefrenceUtil;
import com.wellview.template.utils.Utils;
import com.wellview.template.utils.XulUtils;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by jizi.chen on 2017/8/28.
 */

public class SplashActivity extends BaseActivity implements SplashBehavior.OnStartResponse{

    public static final int AUTO_TURNING_TIME = 2000;

    @BindView(R.id.cb_welcome)
    ConvenientBanner cbWelcome;
    @BindView(R.id.tv_count)
    TextView tvCount;


    private SplashBehavior behavior;

    private boolean hasGO = false;


    @Override
    protected void beforeShow(Bundle savedInstanceState) {
        App.initX5();
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        behavior = (SplashBehavior) BehaviorFactory.create(SplashBehavior.class);
        behavior.setStartListener(this);
        EventBus.getDefault().register(this);
        hasGO = false;
    }

    @Override
    public void bindView() {
        setContentView(R.layout.activity_splash);
    }

    @Override
    public void findAllViews() {

    }

    @Override
    public void setAllListeners() {

    }

    @Override
    public void doProcess() {
        Logger.i(TAG,"isFirstIn()"+isFirstIn());
        if (isFirstIn()) {
            checkPermissions(perms);
            tvCount.setText("立即体验");
        } else {
            tvCount.setText("跳过");
        }
        boolean networkConnected = NetTools.isNetworkConnected(this);
        Logger.i(TAG, "networkConnected >> " + networkConnected);
        Object o = Utils.readObject(App.getInstance(),"splash", "home.txt");
        Logger.i(TAG,"o is null "+(o == null));
        if (o != null) {
            try {
                List<StartBean> beans = ( List<StartBean>) o;
                showBanner(beans);
                Logger.i(TAG,"readObject OK ");
            }catch (Exception e){
                Logger.e(TAG,"readObject Exception ");
                showDefaultBanner();
            }
        }else {
            showDefaultBanner();
        }
        if (networkConnected) {
            behavior.requestStartPage();
        }
    }


    private void showBanner(final List<StartBean> beans) {
        getHandler().post(new Runnable() {
            @Override
            public void run() {
                cbWelcome.setPages(new CBViewHolderCreator() {
                    @Override
                    public Object createHolder() {
                        return new BannerHolder();
                    }
                }, beans)
                        .setPageIndicator(new int[]{R.drawable.shape_coner_green, R.drawable.shape_coner_white})
                        .startTurning(AUTO_TURNING_TIME)
                        .setCanLoop(false);
                if (!isFirstIn()){
                    timerToGoMain();
                }
            }
        });
    }

    private int count = 3;

    private void timerToGoMain() {
        final Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (hasGO){
                            cancel();
                            return;
                        }
                        if (count > 0) {
                            count--;
                            tvCount.setText("跳过");
                        } else {
                            Logger.i(TAG, " count is " + count);
                        }
                        if (count <= 1) {
                            timer.cancel();
                            decideToGo();
                            count = 3;
                        }
                    }
                });
            }
        }, 1000, 1000);
    }

    private void showDefaultBanner() {
        getHandler().post(new Runnable() {
            @Override
            public void run() {
                ArrayList<Integer> res = new ArrayList<>();
                res.add(R.drawable.start1);
                res.add(R.drawable.start2);
                res.add(R.drawable.start3);
                cbWelcome.setPages(new CBViewHolderCreator() {
                    @Override
                    public Object createHolder() {
                        return new BannerDefaultHolder();
                    }
                },res)
                        .setPageIndicator(new int[]{R.drawable.shape_coner_green,R.drawable.shape_coner_white})
                        .startTurning(AUTO_TURNING_TIME)
                        .setCanLoop(false);
                if (!isFirstIn()){
                    timerToGoMain();
                }
            }
        });
    }


    @OnClick({R.id.tv_count})
    public void onViewClicked(View v) {
        switch (v.getId()){
            case R.id.tv_count:
                decideToGo();
                break;
        }
    }

    private void decideToGo() {
        if (!hasGO) {
            goMainActivity();
            hasGO = true;
        }else {
            Logger.i(TAG,"decideToGo already go main"+XulUtils.timestamp_us());
        }
    }

    private void goLoginActivity() {
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
        SharePrefrenceUtil.put(this, "isFirst", "false");
        finish();
    }

    private void goMainActivity() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        SharePrefrenceUtil.put(this, "isFirst", "false");
        finish();
    }

    @Override
    public void startResponseSuccess(List<StartBean> bean) {
        showBanner(bean);
    }

    @Override
    public void startResponseFailed(Exception e) {
        showDefaultBanner();
    }


    class BannerHolder implements Holder<StartBean> {

        private ImageView imageView;

        @Override
        public View createView(Context context) {
            imageView = new ImageView(context);
            imageView.setLayoutParams(new LinearLayout.LayoutParams(ScreenUtil.getScreenWidth(context)
                    ,ScreenUtil.getScreenHeight(context)));
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, int position, StartBean data) {
            Glide.with(context)
                    .load(data.getNetPath())
                    .override(ScreenUtil.getScreenWidth(context),ScreenUtil.getScreenHeight(context))
                    .into(imageView);
        }
    }

    class BannerDefaultHolder implements Holder<Integer> {

        private ImageView imageView;

        @Override
        public View createView(Context context) {
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, int position, Integer data) {
            Glide.with(context)
                    .load(data)
                    .override(ScreenUtil.getScreenWidth(context),ScreenUtil.getScreenHeight(context))
                    .into(imageView);
        }
    }

    public boolean isFirstIn(){
        return "true".equals(SharePrefrenceUtil.get(this, "isFirst", "true"));
    }

    @Override
    protected void onDestroy() {
        SharePrefrenceUtil.put(this, "isFirst", "false");
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageComein(Object o) {
        EventCenter center = (EventCenter) o;
        if (center.getResultCode() == Constant.MESSAGE_X5_INIT){
            boolean isX5 = (boolean) center.getMsg();
            Logger.i(TAG, "onMessageComein is x5" + isX5 + "time" + XulUtils.timestamp_us());
            if (!isX5) {

            }

        }
    }
}
